package com.mifengs.mall.ui.main;


import android.Manifest;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Service;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.mall.Constant;
import com.mifengs.mall.R;
import com.mifengs.mall.adapter.TabClassifyAdapter;
import com.mifengs.commonbase.base.BaseFragment;
import com.mifengs.mall.di.component.DaggerNewHomeFrgComponent;
import com.mifengs.mall.di.module.NewHomeFrgModule;
import com.mifengs.mall.entity.MqttMsg;
import com.mifengs.mall.entity.TabBean;
import com.mifengs.mall.event.PushMsgEvent;
import com.mifengs.mall.ui.login.LoginActivity;
import com.mifengs.mall.util.ImageLoadUtil;
import com.mifengs.mall.util.ToIntentUtil;
import com.mifengs.mall.util.UIUtil;
import com.mifengs.mall.widget.DividerGridItemDecoration;
import com.mifengs.mall.widget.MyTabProvider;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.ogaclejapan.smarttablayout.utils.v4.Bundler;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItem;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItemAdapter;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItems;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.gavinliu.android.lib.shapedimageview.ShapedImageView;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * A simple {@link Fragment} subclass.
 */
public class NewHomeFragment extends BaseFragment<NewHomePresenter> implements NewHomeContract.View, PopupWindow.OnDismissListener, EasyPermissions.PermissionCallbacks,TextToSpeech.OnInitListener{


    @BindView(R.id.smartTabLayout)
    SmartTabLayout mViewPagerTab;
    @BindView(R.id.viewpager)
    ViewPager mViewpager;
    @BindView(R.id.ll_top)
    LinearLayout mLlTop;
    @BindView(R.id.rl_select)
    RelativeLayout mRlSelect;
    @BindView(R.id.fl_tab)
    FrameLayout mFlTab;
    @BindView(R.id.iv_arrow)
    ImageView mIvArrow;
    @BindView(R.id.fg_mask)
    View mFgMask;
    @BindView(R.id.fist_title)
    TextView mFistTitle;
    @BindView(R.id.push_msg_img)
    ShapedImageView pushMsgImg;
    @BindView(R.id.push_msg_text)
    TextView pushMsgText;
    @BindView(R.id.push_llayout)
    LinearLayout pushLlayout;
    @BindView(R.id.reload_img)
    ImageView reloadImg;
    private MqttMsg mqttMsg;
    private MsgThead msgThead;
    private RecyclerView mClassRvList;
    private PopupWindow mClassifyPopuWindow;
    private ValueAnimator mMaskAnimator;
    private TabClassifyAdapter mTabClassifyAdapter;
    private ArrayList<TabBean> mTabBeans = new ArrayList<>();
    public static final int REQUEST_PERMISSION_CAMERA = 1;
    private  boolean isPushLayout= true;
    private TextToSpeech tts;
    public NewHomeFragment() {

    }

    public static NewHomeFragment newInstance() {
        NewHomeFragment fragment = new NewHomeFragment();
        return fragment;
    }

    Handler mHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
//                    pushLlayout.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    if(pushLlayout !=null){
                        pushLlayout.setVisibility(View.GONE);
                        isPushLayout = true;
                    }
                    if (msgThead.isAlive()) {
                        msgThead.interrupt();
                    }
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_new_home, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        init();
        String token = PreferenceUtils.getToken();
        Log.i("app_token",PreferenceUtils.getToken());
        return view;
    }

    private void init() {
        setStatusBarHeight();
        mPresenter.getClassifyData();
        //初始化TTS
        tts = new TextToSpeech(getContext(),this);
    }

    @Override
    public void initInjector() {
        DaggerNewHomeFrgComponent.builder()
                .newHomeFrgModule(new NewHomeFrgModule(this))
                .build()
                .inject(this);
    }


    private void setStatusBarHeight() {
        int statusHeight = UIUtil.getStatusHight();
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mLlTop.getLayoutParams();
        layoutParams.setMargins(0, statusHeight, 0, 0);
    }

    @Override
    public void onDestroyView() {
        if (msgThead != null) {
            if (msgThead.isAlive()) {
                msgThead.interrupt();
            }
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                Glide.get(getContext()).clearMemory();
            }
        });
        super.onDestroyView();
    }


    @OnClick({R.id.reload_img,R.id.rl_home, R.id.iv_arrow, R.id.rl_scan, R.id.ll_search, R.id.fg_mask,R.id.push_llayout,R.id.iv_to_sign,R.id.iv_to_cart})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.rl_home:
                mViewpager.setCurrentItem(0);
                break;
            case R.id.iv_arrow:
                if (mClassifyPopuWindow != null) {
                    if (!mClassifyPopuWindow.isShowing()) {
                        mClassifyPopuWindow.showAsDropDown(mViewPagerTab);
                        popuwindowShowStatus();
                    } else {
                        mClassifyPopuWindow.dismiss();
                    }
                }
                break;
            case R.id.rl_scan:
                //needCamera();
                ARouter.getInstance().build("/moduleone/main").navigation();
                break;
            case R.id.ll_search:
                intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
                break;
            case R.id.fg_mask:
                break;
            case R.id.push_llayout:
                if(mqttMsg.getResults().getRedirectUrl() !=null){
                    ToIntentUtil.toCommonIntent(mqttMsg.getResults().getRedirectUrl(), getContext());
                }
                break;
            case R.id.iv_to_sign:
                if(PreferenceUtils.getLoginStatus()){
                    ToIntentUtil.toCommonIntent(Constant.H5_sign,getActivity());
                }else{
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                }
                break;
            case R.id.iv_to_cart:
                ToIntentUtil.toCommonIntent(Constant.H5_CART,getActivity());
                break;
            case R.id.reload_img:
                mPresenter.getClassifyData();
                break;

        }
    }


    //方法：发送网络请求，获取百度首页的数据。在里面开启线程
    private void sendRequestWithHttpClient() {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    URL url = new URL("https://www.mifengs.com/es/querySearchs");
//                    //得到connection对象。
//                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//                    //设置请求方式
//                    connection.setRequestMethod("GET");
//                    //连接
//                    connection.connect();
//                    //得到响应码
//                    int responseCode = connection.getResponseCode();
//                    if(responseCode == HttpURLConnection.HTTP_OK){
//                        //得到响应流
//                        InputStream inputStream = connection.getInputStream();
//                        //将响应流转换成字符串
//                    }
//
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();

    }


    public void initPopuWindow() {
        View classifyView = LayoutInflater.from(getActivity()).inflate(R.layout.tab_home_popuwindow, null);
        mClassRvList = classifyView.findViewById(R.id.classify_list);
        mClassRvList.setLayoutManager(new GridLayoutManager(getContext(), 4));
        mClassRvList.addItemDecoration(new DividerGridItemDecoration(getContext()));
        mTabClassifyAdapter = new TabClassifyAdapter();
        mTabClassifyAdapter.setNewData(mTabBeans);
        mClassRvList.setAdapter(mTabClassifyAdapter);
        mClassifyPopuWindow = new PopupWindow(classifyView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mClassifyPopuWindow.setOnDismissListener(this);
        mClassifyPopuWindow.setAnimationStyle(R.style.showPopupAnimation);
        mTabClassifyAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mViewpager.setCurrentItem(position);
                mClassifyPopuWindow.dismiss();
            }
        });
    }


    public void popuwindowShowStatus() {
        mFlTab.setVisibility(View.GONE);
        mRlSelect.setVisibility(View.VISIBLE);
        mIvArrow.setImageResource(R.drawable.ic_arrow_up);
        mIvArrow.setBackgroundColor(0xFFC0C1C0);
        mFgMask.setVisibility(View.VISIBLE);
        fgMaskAnimation(1);
    }

    public void popuwindowHideStatus() {
        mFlTab.setVisibility(View.VISIBLE);
        mRlSelect.setVisibility(View.GONE);
        mIvArrow.setImageResource(R.drawable.ic_arrow_down);
        mIvArrow.setBackgroundColor(Color.WHITE);
        mFgMask.setVisibility(View.GONE);
        fgMaskAnimation(0);
    }

    public void fgMaskAnimation(int type) { //1 是开 0 是消失
        if (mMaskAnimator != null)
            mMaskAnimator.cancel();
        if (type == 1) {
            mMaskAnimator = ObjectAnimator.ofFloat(0, 0.3f);
        } else if (type == 0) {
            mMaskAnimator = ObjectAnimator.ofFloat(0.3f, 0);
        }
        mMaskAnimator.setInterpolator(new LinearInterpolator());
        mMaskAnimator.setDuration(500);//持续时间
        mMaskAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float i = (float) animation.getAnimatedValue();
                if (mFgMask != null)
                    mFgMask.setAlpha(i);
            }
        });
        mMaskAnimator.start();
    }

    @Override
    public void onDestroy() {
        if (mMaskAnimator != null) {
            mMaskAnimator.cancel();
        }
        super.onDestroy();

    }

    @Override
    public void onDismiss() {
        popuwindowHideStatus();
    }


    @Override
    public void setClassifyData(final ArrayList<TabBean> tabBeanList) {
        this.mTabBeans = tabBeanList;
        if (tabBeanList.size() > 0) {
            mFistTitle.setText(tabBeanList.get(0).getTitle());
        }
        FragmentPagerItems pages = new FragmentPagerItems(getContext());
        final MyTabProvider myTabProvider = new MyTabProvider(mTabBeans, getContext());
        mViewPagerTab.setCustomTabView(myTabProvider);
        for (int i = 0; i < tabBeanList.size(); i++) {
            pages.add(FragmentPagerItem.of(tabBeanList.get(i).getTitle(), FloorFragment.class, new Bundler().putSerializable("tab", tabBeanList.get(i)).get()));
        }
        FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter(
                getChildFragmentManager(), pages);
        initPopuWindow();
        mViewpager.setAdapter(adapter);
        mViewpager.setOffscreenPageLimit(2);
        mViewPagerTab.setViewPager(mViewpager);
        mViewPagerTab.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    mFistTitle.setTextColor(0xFFF4302E);
                } else {
                    mFistTitle.setTextColor(ContextCompat.getColor(getContext(), R.color.custom_light_txt_color));
                }
                ArrayList<Integer> positionList = myTabProvider.getmImagePosition();
                for (int imagePosition : positionList) {
                    View v = mViewPagerTab.getTabAt(imagePosition);
                    TextView tvTitle = v.findViewById(R.id.title);
                    ImageView ivTitle = v.findViewById(R.id.iv_title);
                    if (imagePosition == position) {
                        tvTitle.setVisibility(View.VISIBLE);
                        ivTitle.setVisibility(View.GONE);
                        tvTitle.setText(tabBeanList.get(imagePosition).getTitle());
                    } else {
                        tvTitle.setVisibility(View.GONE);
                        ivTitle.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void reload(boolean isShow) {
        if(isShow){
            reloadImg.setVisibility(View.INVISIBLE);
        }else{
            reloadImg.setVisibility(View.VISIBLE);
        }
    }

    @AfterPermissionGranted(REQUEST_PERMISSION_CAMERA)
    public void needCamera() {
        String[] perms = {Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(getActivity(), perms)) {
            startScan();
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.need_camera_permission),
                    REQUEST_PERMISSION_CAMERA, perms);
        }
    }

    private void startScan() {
        Intent intent = new Intent(getContext(), ScanActivity.class);
        startActivity(intent);
    }

    @Override
    public void onPermissionsGranted(int i, List<String> list) {

    }

    @Override
    public void onPermissionsDenied(int i, List<String> list) {

    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden & mClassifyPopuWindow != null) {
            if (mClassifyPopuWindow.isShowing()) mClassifyPopuWindow.dismiss();
        }
    }

    @Override
    public void onInit(int status) {
        // 判断是否转化成功
        if (status == TextToSpeech.SUCCESS){
            //默认设定语言为中文，原生的android貌似不支持中文。
            int result = tts.setLanguage(Locale.CHINESE);
//            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
//                Toast.makeText(getContext(), "中文不支持哦", Toast.LENGTH_SHORT).show();
//            }else{
//                //不支持中文就将语言设置为英文
//                tts.setLanguage(Locale.US);
//            }
        }
    }


    public class MsgThead extends Thread {
        @Override
        public void run() {
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                if (msgThead.isAlive()) {
                    msgThead.interrupt();
                }
            }
            Message msg = new Message();
            msg.what = 2;
            mHandle.sendMessage(msg);
        }
    }

    @Override
    public void onPause() {
        if (msgThead != null) {
            if (msgThead.isAlive()) {
                msgThead.interrupt();
            }
        }
        super.onPause();
    }

    private void audioSpeak(MqttMsg mqttMsg){
        AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Service.AUDIO_SERVICE);
        int max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, max,0);
        tts.setPitch(1.5f); // 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
        tts.speak(mqttMsg.getResults().getMessage().toString(), TextToSpeech.QUEUE_FLUSH, null);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(PushMsgEvent event) {
        mqttMsg = event.getMqttMsg();
        switch (event.action){
            case PushMsgEvent.MOPAO_MSG:

                if(isPushLayout){
                    isPushLayout = false;
                    if(pushLlayout !=null){
                        pushLlayout.setVisibility(View.VISIBLE);
                    }
                    ImageLoadUtil.displayImage(getContext(), mqttMsg.getResults().getImgUrl().trim(), pushMsgImg);
                    pushMsgText.setText(mqttMsg.getResults().getContent());
                    msgThead = new MsgThead();
                    msgThead.start();
                }
                break;
            case PushMsgEvent.VOICE_MSG:
                audioSpeak(mqttMsg);
                    break;
        }

    }
}
